﻿using D.B.Data.API.Applications.Command.RoleCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;

namespace D.B.Data.API.Applications.CommandHandler.RoleCommandHandler
{
    public class UpDataRoleCommandHandler : IRequestHandler<UpDataRoleCommand, APIResult<object>>
    {

        private readonly IBaseRepository<RoleModel> RoleRepository;

        public UpDataRoleCommandHandler(IBaseRepository<RoleModel> roleRepository)
        {
            RoleRepository = roleRepository;
        }

        public Task<APIResult<object>> Handle(UpDataRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var data = RoleRepository.GetAll().Where(s=>s.RoleName==request.RoleName&&s.Id!=request.Id && !s.IsDel);
            if(data.Count()>0)
            {
                result.Code = EnumCode.File ;
                result.Msg = "角色名称重复";
                return Task.FromResult(result);
            }

           

            var res = RoleRepository.GetAll().FirstOrDefault(s => s.Id== request.Id);
            

            res.RoleName= request.RoleName;
            res.UpDataUserId=request.UserId;
            res.UpDataTime = DateTime.Now;

            var count= RoleRepository.Update(res);

            if(count>0)
            {
                result.Code=EnumCode.Ok;
                result.Msg = "修改成功";
                result.Data=count;
                return Task.FromResult(result);
            }
            result.Code = EnumCode.File;
            result.Msg = "修改失败";
            result.Data = count;
            return Task.FromResult(result);
        }
    }
}
